const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient

function MongodbConnector () {
  this.dbs = {}
}

MongodbConnector.prototype.init = async function (dbsConf) {
  this.dbs_conf = dbsConf
  const promises = Object.keys(dbsConf).map(name => (async () => {
    console.log(`init ${name}`)
    const dbUrl = dbsConf[name].url
    try {
      this.dbs[name] = await MongoClient.connect(dbUrl, {
        useNewUrlParser: true,
        minSize: 10,
        useUnifiedTopology: true
      })
    } catch (e) {
      throw new Error(`Init ${name} failed: ${e.message}`)
    }
  })())
  await Promise.all(promises)
}

MongodbConnector.prototype.use = function (name) {
  return this.dbs[name].db(this.dbs_conf[name].dbName)
}

module.exports = MongodbConnector
